package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.common.core.constant.enums.AllAuditActionStatusEnum;
import com.engine4cloud.tdf.common.core.constant.enums.AuditBusinessTypeEnum;
import com.engine4cloud.tdf.common.core.constant.enums.CorFileTypeEnum;
import com.engine4cloud.tdf.common.core.constant.enums.NormalAuditActionStatusEnum;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.data.web.query.Pages;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.data.web.response.PageInfo;
import com.engine4cloud.tdf.common.data.web.response.Params;
import com.engine4cloud.tdf.common.security.service.TdfUser;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.SpAccessSpecificConvert;
import com.engine4cloud.tdf.supervision.dto.SpAccessSpecificVerifyDTO;
import com.engine4cloud.tdf.supervision.dto.create.SpAccessSpecificCreateDTO;
import com.engine4cloud.tdf.supervision.dto.create.SpAuditActionResultCreateDTO;
import com.engine4cloud.tdf.supervision.dto.query.JzdxFileQueryDTO;
import com.engine4cloud.tdf.supervision.dto.query.SpAccessSpecificQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxResultDTO;
import com.engine4cloud.tdf.supervision.dto.result.SpAccessSpecificResultDTO;
import com.engine4cloud.tdf.supervision.dto.update.SpAccessSpecificUpdateDTO;
import com.engine4cloud.tdf.supervision.dto.update.SpNormalPreActionUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.SpAccessSpecificEntity;
import com.engine4cloud.tdf.supervision.mapper.SpAccessSpecificMapper;
import com.engine4cloud.tdf.supervision.service.JzdxFileService;
import com.engine4cloud.tdf.supervision.service.JzdxService;
import com.engine4cloud.tdf.supervision.service.SpAccessSpecificService;
import com.engine4cloud.tdf.supervision.service.SpAuditResultService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 进入特定区域
 *
 * @author wenjie
 * @date 2024-05-31 10:24:42
 */
@Service
public class SpAccessSpecificServiceImpl extends ServiceImpl<SpAccessSpecificMapper, SpAccessSpecificEntity> implements SpAccessSpecificService {
    @Resource
    private JzdxService jzdxService;

    @Resource
    private SpAuditResultService auditResultService;

    @Resource
    private JzdxFileService fileService;

    @Override
    public PageInfo<SpAccessSpecificResultDTO> getPageList(Params pageable, SpAccessSpecificQueryDTO dto) {
        IPage<SpAccessSpecificEntity> page = super.page(Pages.page(pageable), wrapper(dto));
        return Pages.convert(page, SpAccessSpecificConvert.INSTANCE::convert);
    }

    @Override
    public List<SpAccessSpecificResultDTO> findListByPreActions(SpAccessSpecificVerifyDTO dto) {
        return super.list(wrapperVerify(dto)).stream().map(SpAccessSpecificConvert.INSTANCE::convert).toList();
    }

    @Override
    public SpAccessSpecificResultDTO getByBatch(String batch) {
        return SpAccessSpecificConvert.INSTANCE.convert(super.getOne(wrapper(new SpAccessSpecificQueryDTO(batch))));
    }

    @Override
    public SpAccessSpecificResultDTO getById(Long id) {
        SpAccessSpecificResultDTO result = Optional.ofNullable(SpAccessSpecificConvert.INSTANCE.convert(super.getById(id)))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));
        //设置法律文书信息
        this.setInstrumentList(result);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(SpAccessSpecificCreateDTO dto) {
        JzdxResultDTO dx = Optional.ofNullable(jzdxService.getByCode(dto.getRybh()))
                .orElseThrow(() -> new ValidateCodeException("矫正对象数据不存在"));

        TdfUser user = SecurityUtils.getUser();
        SpAccessSpecificEntity entity = SpAccessSpecificConvert.INSTANCE.create(dto, dx.getTenantId(), NormalAuditActionStatusEnum.CREATE);
        //保存主体信息
        super.save(entity);
        //保存文件信息
        this.saveInstrumentList(dto, entity, user);
        //保存审核信息
        return auditResultService.create(
                new SpAuditActionResultCreateDTO(
                        entity.getRybh(),
                        entity.getLcbh(),
                        "",
                        AuditBusinessTypeEnum.ACCESS_SPECIFIC,
                        AllAuditActionStatusEnum.CREATE,
                        user.getUsername(),
                        entity.getTenantId(),
                        user.getDeptId()
                ));
    }

    @Override
    public Boolean update(SpAccessSpecificUpdateDTO dto) {
        SpAccessSpecificEntity old = Optional.ofNullable(super.getById(dto.getId()))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        TdfUser user = SecurityUtils.getUser();
        SpAccessSpecificEntity entity = SpAccessSpecificConvert.INSTANCE.update(dto);
        //保存主体信息
        super.updateById(entity);
        //保存文件信息
        this.updateInstrumentList(dto, old, user);
        return true;
    }

    @Override
    public void changeAction(SpNormalPreActionUpdateDTO dto) {
        SpAccessSpecificEntity entity = Optional.ofNullable(this.getOne(wrapper(new SpAccessSpecificQueryDTO(dto.getRybh(), dto.getLcbh()))))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        entity.setPreAction(dto.getAction());
        super.updateById(entity);
    }

    public void saveInstrumentList(SpAccessSpecificCreateDTO dto, SpAccessSpecificEntity entity, TdfUser user) {
        fileService.batchSaveFile(new JzdxFileQueryDTO(entity.getRybh(), entity.getLcbh(), CorFileTypeEnum.CORRECTOR_ACCESS_SPECIFIC), dto.getInstrumentList(), user);
    }

    public void updateInstrumentList(SpAccessSpecificUpdateDTO dto, SpAccessSpecificEntity entity, TdfUser user) {
        fileService.batchUpdateFile(new JzdxFileQueryDTO(entity.getRybh(), entity.getLcbh(), CorFileTypeEnum.CORRECTOR_ACCESS_SPECIFIC), dto.getInstrumentList(), user);
    }

    private void setInstrumentList(SpAccessSpecificResultDTO dto) {
        JzdxFileQueryDTO query = new JzdxFileQueryDTO(dto.getRybh(), dto.getLcbh(), CorFileTypeEnum.CORRECTOR_ACCESS_SPECIFIC);
        dto.setInstrumentList(fileService.findList(query));
    }

    private LambdaQueryWrapper<SpAccessSpecificEntity> wrapper(SpAccessSpecificQueryDTO query) {
        LambdaQueryWrapper<SpAccessSpecificEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(SpAccessSpecificEntity::getId, v));
        Queries.accept(query.getRybh(), v -> wrapper.eq(SpAccessSpecificEntity::getRybh, v));
        Queries.accept(query.getLcbh(), v -> wrapper.eq(SpAccessSpecificEntity::getLcbh, v));
        Queries.accept(query.getPreAction(), v -> wrapper.eq(SpAccessSpecificEntity::getPreAction, v));
        return wrapper;
    }

    private LambdaQueryWrapper<SpAccessSpecificEntity> wrapperVerify(SpAccessSpecificVerifyDTO query) {
        LambdaQueryWrapper<SpAccessSpecificEntity> wrapper = Queries.lambda();
        Queries.accept(query.getRybh(), v -> wrapper.eq(SpAccessSpecificEntity::getRybh, v));
        Queries.accept(query.getLocTime(), v -> wrapper.lt(SpAccessSpecificEntity::getSqjrrq, v)
                .ge(SpAccessSpecificEntity::getSqjsrq, v));
        Queries.accept(query.getEnumList(), v -> wrapper.in(SpAccessSpecificEntity::getPreAction, v));
        return wrapper;
    }
}